/**
 * @class Controller that handles the JSON serialized calls that come from the server.
 * Generally this calls will be assembled by the {@link http://essaylibrarydocs/api/jsCall/JsCall.html JsCall PHP class}
 */
$(document).ajaxComplete(
  function(e,xhr,s) {
    $('#'+s.loadingElementId).hide();
  }
);
JsonC = new function(){
  this.visibleCallIndicators = {};
  /**
  * @param action must be a symfony action like 'user/show'
  * @param params must be an object with names and values, ex:  {"userId":45,"parentId":38}
  */
  this.callSfAction = function (action, params, loadingElementId) {
    var url = JsonC.genSfUrl(action,params);
    $('#'+loadingElementId).show();
    $.ajax({
      url: url,
      dataType : 'json',
      data : {},
      success : JsonC.receiveJsonCall,
      error: JsonC.receiveJsonCallError,
      loadingElementId : loadingElementId
    });
  }


  this.submitForSfAction = function (action, params, formId, loadingElementId) {
    var form = $('#'+formId);
    if(!(form.length)) {
      UtilC.showDebugMessage("Could not find form with id = '"+formId+"'");
    }
    form = form[0];


    var hasFile = false;
    var files = $('input:file', $(form)).fieldValue();
    for (var j=0; j < files.length; j++) {
        if (files[j]) {
            hasFile = true;
        }
    }
    if(hasFile) {
      if(params === null) params = {};
      params.iframeAjaxUpload = true;
    }
    var url = JsonC.genSfUrl(action,params);
    form.action = url;
    JsonC.disableFormSubmitButton($(form).attr('id'));
    $('#'+loadingElementId).show();
    $(form).ajaxForm({
      dataType: 'json',
      success: JsonC.receiveJsonCall,
      error: JsonC.receiveJsonCallError,
      loadingElementId : loadingElementId
    });

    $(form).submit();
  }

  /**
   * Dinamically makes a call to execute all the commands comming from a php-js json rmi.
   * Call the executeJsonCommand for each of the commands.
   */
  this.receiveJsonCall = function(json) {
    JsonC.enableFormSubmitButton(arguments[2]);
  	if(!json.commands) {
  	  alert('The json response contains no commands.');
  	}
  	try {
      $.each(json.commands,JsonC.executeJsonComand);
    }
    catch(e) {
      if(e.name === 'JsonComandControllerNotFound' || e.name === 'JsonComandFunctionNotFound') {
        UtilC.handleException(e);
      }
      else {
        throw e;
      }
    }
  }

  /**
   * Handler for a JSON call that results on an error.
   */
  this.receiveJsonCallError = function(XMLHttpRequest, textStatus, errorThrown) {
    //JsonC.enableFormSubmitButton(arguments[2]);
    $(".disableOnRequest").removeAttr("disabled");
  	if(textStatus == 'parsererror') {
  	  UtilC.showBigFeedback({"message":'Unable to parse received JSON.'+XMLHttpRequest.responseText});
  	}
  	else {
  	  UtilC.showBigFeedback({"message":'Error receiving JSON call: ' + textStatus + XMLHttpRequest.responseText});
  	}
  }

  this.disableFormSubmitButton = function(formId) {
    $("#" + formId + " .disableOnRequest").attr("disabled","disabled");
  }

  this.enableFormSubmitButton = function(element) {
    var formId = $(element).attr('id');
    $("#" + formId + " .disableOnRequest").removeAttr("disabled");
  }


  /**
   * Execute each command comming from a php-js json rmi.
   * See receiveJsonCall.
   */
  this.executeJsonComand = function(i,item) {
    //eval the controller to see if it exists
    try{
      var ctr = eval(item.controller);
    }
    catch(e) {
      throw {
        name: 'JsonComandControllerNotFound',
        message: 'Could not find the requested js controller (receiving JsonCall):"' + item.controller + '"'
      };
    }

    //eval the action function
    var actionName = item.action;
    if(typeof(ctr[actionName]) !== 'function') {
      throw {
        name: 'JsonComandFunctionNotFound',
        message: 'Could not find the requested function: "'+item.controller+'.'+actionName+'()"'
      };
    }
    else {
      ctr[actionName](item.params);
    }
  }

  this.genSfUrl = function(action,params) {
    var url = base_url + action;
    url += JsonC.renderParamsUrl(params);
    return url;
  }

  this.renderParamsUrl = function(params) {
    var ret = '';
    if(params != undefined) {
      for(i in params) {
        ret += '/' + i + '/' + UtilC.urlencode(params[i]);
      }
    }
    return ret;
  }


}